<script setup>
import * as echarts from 'echarts';
import { onMounted, ref } from 'vue';
import axios from 'axios';

const echartBar = ref(null);
let options = ref([]);

// 函数: 设置折线图
function chartBartInit() {
  const myChart = echarts.init(echartBar.value, "dark", {
    width: 480,
    height: 400,
  });

  // 转换 API 数据为 xAxis 和 seriesData
  const xAxisData = options.value.map(item => item.name);
  const seriesData = options.value.map(item => item.value);

  const option = {
    color: ['#80FFA5', '#00DDFF', '#37A2FF', '#FF0087', '#FFBF00'],
    title: {
      text: '图书类目数量分析',
      left: 'center',
      top: 20,
      textStyle: {
        color: '#FFF',
        fontWeight: 'bold',
        fontSize: '20px'
      },
    },
    tooltip: {
      trigger: 'axis',
      axisPointer: { type: 'cross' }
    },
    legend: {
      data: ['数量']
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      containLabel: true
    },
    xAxis: {
      type: 'category',
      data: xAxisData
    },
    yAxis: {
      type: 'value'
    },
    series: [
      {
        name: '数量',
        type: 'line',
        stack: 'Total',
        smooth: true,
        lineStyle: {
          width: 3,
          color: '#47f62c' // 设置线条颜色
        },
        showSymbol: true,
        symbol: 'circle', // 点的形状
        symbolSize: 10, // 点的大小
        itemStyle: {
          color: '#FF0087', // 点的颜色
          borderWidth: 3, // 点的边框宽度
          borderColor: '#FF0000' // 点的边框颜色
        },
        emphasis: {
          focus: 'series'
        },
        data: seriesData
      }
    ]
  };

  myChart.setOption(option);
}

// 函数: 获取数据
function getData() {
  // 调用 API 接口
  axios.get('/book-api/queryAllCategoryCountAnalysis')
      .then(response => {
        options.value = response.data.data;  // 假设接口返回的数据结构为 { data: [...] }
        chartBartInit();  // 调用初始化函数渲染图表
      })
      .catch(error => {
        console.error('Error fetching data:', error);
      });
}

onMounted(() => {
  getData(); // 组件挂载时调用获取数据函数
});
</script>

<template>
  <div id="d2"> <!-- 外层 div，id 为 d2 -->
    <div ref="echartBar" style="width: 100%; height: 100%;"></div>
  </div>
</template>

<style scoped>
.echart-bar {
  width: 100%;
  height: 100%;
  margin: 20px 0;
}

#d2 {
  padding: 20px; /* 可根据需要调整 d2 的样式 */
  background-color: #003b51; 
}
</style>
